package com.nerve.android.cloudoffice.app.activity.task;

import java.util.Calendar;
import java.util.Date;

import org.nerve.android.NerveActivityGroup;
import org.nerve.android.annotation.Acvitity;
import org.nerve.android.annotation.ViewOnId;
import org.nerve.android.ui.dialog.DialogHelper.ConfirmListener;
import org.nerve.android.ui.dialog.SpinnerDialog;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.nerve.android.cloudoffice.OfficeApplication;
import com.nerve.android.cloudoffice.R;
import com.nerve.android.cloudoffice.app.NavigationActivity;
import com.nerve.android.cloudoffice.app.activity.assist.UserSelectActivity;
import com.nerve.android.cloudoffice.app.group.IndexGroupActivity;
import com.nerve.android.cloudoffice.common.Const;
import com.nerve.android.cloudoffice.common.Reply;
import com.nerve.android.cloudoffice.common.Resource;
import com.nerve.android.cloudoffice.domain.Task;
import com.nerve.android.cloudoffice.domain.User;
import com.nerve.android.cloudoffice.service.data.TaskData;

/**
 * @project: Cloudoffice
 * @file: AddTaskActivity.java
 * @package: com.nerve.android.cloudoffice.app.activity.task
 * @description:
 *
 * @author: 集成显卡	1053214511@qq.com
				IBM GDC, zengxm@cn.ibm.com
 * @date&time: Aug 16, 2013
 * @change log:
 */
@SuppressLint("HandlerLeak")
@Acvitity(layout=R.layout.activity_task_add)
public class AddTaskActivity extends NavigationActivity implements OnClickListener, ConfirmListener{
	
	public static final String LAST_TASK = "last_task";
	
	public static final int SELEC_USER = 0;
	public static final int SELECT_DATE = 1;
	public static final int SELECT_LEVEL = 2;
	
	@ViewOnId(id=R.id.name)
	private EditText nameET;
	@ViewOnId(id=R.id.worker, clickListener="this")
	private EditText workerET;
	@ViewOnId(id=R.id.endDate, clickListener="this")
	private EditText endDateET;
	@ViewOnId(id=R.id.level, clickListener="this")
	private EditText levelET;
	@ViewOnId(id=R.id.remark)
	private EditText remarkET;
	@ViewOnId(id=R.id.tag)
	private EditText tagET;
	@ViewOnId(id=R.id.project)
	private EditText projectET;
	@ViewOnId(id=R.id.sender)
	private EditText senderET;
	
	@ViewOnId(id=R.id.acceptType, clickListener="this")
	protected TextView autoAccept;
	private Drawable autoDrawable;
	
	private boolean isAccept = true;
	
	private int workerId;//保存了接受人id
	private int level;//任务重要度
	private Date endDate;
	
	private SpinnerDialog levelSpinnerDialog;
	private SpinnerDialog dateSpinnerDialog;
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			hideProgressDialog();
			switch(msg.what){
			case WORKER_FAIL:
				toast(Const.ERROR);
				break;
			case WORKER_OK:
				toast("任务创建成功");
				putData(LAST_TASK, 1);
				NerveActivityGroup group = getActivityGroup(IndexGroupActivity.class);
				group.back();
				break;
			}
		}
	};
	
	@Override
	protected void initUI() {
		setNavTitle("新增任务");
		customNavigateRightButton("保存", true);
		
		
		//默认的接单人是自己
		User user = OfficeApplication.USER;
		if(user != null){
			workerET.setText(user.getDepartment().getName() + Const.SPLIT + user.getName());
			workerId = user.getId();
			
			//发起人就是当前登录用户
			senderET.setText(user.getName());
		}
		
	}
	
	@Override
	protected void onNavigateRightButtonClick() {
		if(isEmpty(nameET)){
			toast("任务标题不能为空");
			return ;
		}
		if(workerId <= 0){
			toast("请选择任务接受人");
			return ;
		}
		if(endDate == null){
			toast("请选择任务到期时间");
			return ;
		}
		
		showProgressDialog(null, "正在保存任务信息，请稍候...");
		new AddWorker().execute();
	}
	
	@Override
	protected void onNavigateBackButtonClick() {
		NerveActivityGroup group = getActivityGroup(IndexGroupActivity.class);
		group.back();
	}
	
	private void changeAutoDrawable(){
		if(isAccept){
			if(autoDrawable == null){
				autoDrawable = getResources().getDrawable(R.drawable.ico_ok);
				autoDrawable.setBounds(0, 0, autoDrawable.getMinimumWidth(), autoDrawable.getMinimumHeight());
			}
			autoAccept.setCompoundDrawables(null, null, autoDrawable, null);
		}else{
			autoAccept.setCompoundDrawables(null, null, null, null);
		}
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		
		case R.id.acceptType:
			isAccept = !isAccept;
			changeAutoDrawable();
			break;
		case R.id.worker:
			Intent intent = new Intent(this, UserSelectActivity.class);
			startActivityForResult(intent, SELEC_USER);
			break;
		case R.id.endDate:
			if(dateSpinnerDialog == null){
				dateSpinnerDialog = new SpinnerDialog(this, Resource.Task.END_DATE);
				dateSpinnerDialog.setCode(SELECT_DATE);
				dateSpinnerDialog.setTitle("选择到期时间");
				dateSpinnerDialog.setConfirmListener(this);
			}
			dateSpinnerDialog.show();
			break;
		case R.id.level:
			if(levelSpinnerDialog == null){
				levelSpinnerDialog = new SpinnerDialog(this, Resource.Task.LEVEL);
				levelSpinnerDialog.setCode(SELECT_LEVEL);
				levelSpinnerDialog.setTitle("选择任务重要度");
				levelSpinnerDialog.setConfirmListener(this);
			}
			levelSpinnerDialog.show();
			break;
		}
	}

	@Override
	public void onConfirmClick(int position, Object obj) {
		if((Integer)obj == SELECT_DATE){
			endDate = new Date();
			
			int day = position + 1;
			if(position == 3)
				day = 7;
			else if(position == 4)
				day = 14;
			
			Calendar c = Calendar.getInstance();
			c.add(Calendar.DAY_OF_YEAR, day);
			endDate = c.getTime();
			
			Const.log("到期时间："+ endDate.toLocaleString());
			
			endDateET.setText(Resource.Task.END_DATE[position]);
		}else{
			levelET.setText(Resource.Task.LEVEL[position]);
			level = position;
		}
	}
	
	/**
	 * 选择用户时的返回
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data == null)
			return ;
		
		if(requestCode == SELEC_USER){
			String info = data.getStringExtra(UserSelectActivity.INFO);
			int id = data.getIntExtra(UserSelectActivity.ID, -1);
			
			if(id > 0){
				workerET.setText(info);
				workerId = id;
			}
		}
	}
	
	private class AddWorker extends AsyncTask<Void, Void, Integer>{

		@Override
		protected Integer doInBackground(Void... params) {
			Task t = new Task();
			t.setTitle(getText(nameET));
			t.setEndDate(endDate);
			t.setStartDate(new Date());
			t.setLevel(level);
			t.setWorkUser(workerId+"");
			t.setRemark(getText(remarkET));
			t.setTag(getText(tagET));
			t.setProject(getText(projectET));
			
			if(isAccept){
				t.setLoaction(Task.FORCE);
			}else{
				t.setLoaction(Task.WAIT_ACCEPT);
			}
			
			Reply re = TaskData.add(t);
			if(re.isError()){
				Const.ERROR = re.getMessage().toString();
				return WORKER_FAIL;
			}
			
			return WORKER_OK;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			handler.sendEmptyMessage(result);
		}
	}
}